<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Material;
use AppBundle\Entity\MaterialOrder;
use AppBundle\Entity\Product;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function indexAction(Request $request)
    {
        // replace this example code with whatever you need
        return $this->render('default/index.html.twig', [
            'base_dir' => realpath($this->getParameter('kernel.project_dir')) . DIRECTORY_SEPARATOR,
        ]);
    }

    /**
     * @return \Doctrine\Common\Persistence\ObjectManager
     */
    protected function getEntityManager()
    {
        return $this->getDoctrine()->getManager();
    }

    /**
     * @param string $message
     * @param array $data
     * @return JsonResponse
     */
    protected function responseSuccess(string $message = '', array $data = [])
    {
        return new JsonResponse([
            'code' => 0,
            'message' => $message,
            'data' => $data,
        ]);
    }

    /**
     * @param int $code
     * @param string $message
     * @return JsonResponse
     */
    protected function responseError(int $code, string $message = '')
    {
        return new JsonResponse([
            'code' => $code,
            'message' => $message,
            'data' => [],
        ]);
    }


    /**
     * @param int $pid product id
     * @return Product
     */
    protected function findProductOrResponseError($pid): Product
    {
        $em = $this->getDoctrine()->getManager();
        /** @var Product $product */
        $product = $em->getRepository(Product::class)->find($pid);
        if (!$product) $this->responseError(4001, "No product found for id {$pid}");
        return $product;
    }

    /**
     * @param int $mid material id
     * @return Material
     */
    protected function findMaterialOrResponseError($mid): Material
    {
        $em = $this->getDoctrine()->getManager();
        /** @var Material $material */
        $material = $em->getRepository(Material::class)->find($mid);
        if (!$material) $this->responseError(4002, "No product found for id {$mid}");
        return $material;
    }

    /**
     * @param int $oid material order id
     * @return MaterialOrder
     */
    protected function findMaterialOrderOrResponseError($oid): MaterialOrder
    {
        $em = $this->getDoctrine()->getManager();
        /** @var MaterialOrder $order */
        $order = $em->getRepository(MaterialOrder::class)->find($oid);
        if (!$order) $this->responseError(4002, "No material order found for id {$oid}");
        return $order;
    }

}
